import {
  ChangeDetectionStrategy,
  Component,
  Inject,
  InjectionToken,
  Injector,
  Optional,
} from '@angular/core'
import { AdBaseGridCellComponent } from '../../class/base.grid.cell'
import { MyICellRendererParams, RenderTemplateType } from '../../class/grid.interface'
import { TypeUtils } from 'monk-design/utils'
import { AD_AUTH, AdAuth } from 'monk-design/config'

@Component({
  selector: 'ad-cell-template',
  templateUrl: './cell-template.component.html',
  styleUrls: ['./cell-template.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdCellTemplateComponent<T = any, D = any> extends AdBaseGridCellComponent<T, D> {
  params: MyICellRendererParams<T, D>

  constructor(@Optional() @Inject(AD_AUTH) private adAuth: AdAuth, private injector: Injector) {
    super()
  }

  /**
   * 获取渲染列表数据
   */
  get cellRenderList(): RenderTemplateType<T, D>[] {
    return (
      this.params.cellRenderList?.map((item) => {
        //默认标签为span
        item.tag = item.tag || 'span'
        return item
      }) || []
    )
  }

  /**
   * 处理回调函数
   * @param eventParams
   * @param event
   * @returns
   */
  handleEventFunc(eventParams, event) {
    if (TypeUtils.getType(eventParams) === 'function') {
      return eventParams(this, event)
    }
  }

  /**
   * 属性处理函数
   * @param attrValue 传入的属性值
   * @param allowedValueTypes 允许的属性类型
   * @param defaultValue 默认属性值
   * @returns
   */
  handleAttrFunc(
    attrValue,
    allowedValueTypes: Array<typeof TypeUtils.AllType[number]> = [],
    defaultValue: any = ''
  ) {
    //如果属性值为函数 调用函数返回函数的结果
    if (TypeUtils.getType(attrValue) === 'function') {
      return attrValue(this)
      //如果属性值在允许值之内 返回属性值
    } else if (allowedValueTypes.includes(TypeUtils.getType(attrValue))) {
      return attrValue
    }
    //都不满足返回默认值
    return defaultValue
  }

  auth(auth: string) {
    if (!auth) {
      return true
    }
    return this.adAuth(auth, this.injector)
  }
}
